
/*
 * 文件名：AESUntils.java 版权：Copyright by www.rsrtech.net 描述： 修改人：郑净云 修改时间：2017年7月27日
 */

package com.snailhd.framework.util.base;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

@SuppressWarnings("restriction")
public class AESUtil {


	private static final String KEY = "djfjsd1aAhd92s.hs,djd@^&";


	public static String encry(String text ) throws Exception{
		return encry(text,KEY);
	}


	/**
	 * 加密 AES-->Base64
	 * @param text 要加密的文本
	 * @param key 加密密钥
	 * @return 加密字符串
	 * @throws Exception 异常
	 */
	public static String encry(String text, String key) throws Exception {
		byte[] byteText = text.getBytes(StandardCharsets.UTF_8);
		byte[] byteCipher = aesOpt(byteText, key, Cipher.ENCRYPT_MODE);
		return base64Encry(byteCipher).replace("\n", "").replace("\r", "");
	}


	public static String decry(String ciphertext) throws Exception {
		return decry(ciphertext, KEY);
	}

	/**
	 * 解密 base64-->AES
	 * 
	 * @param ciphertext 被加密的字符串
	 * @param key 密钥
	 * @return 明文
	 */
	public static String decry(String ciphertext, String key) throws Exception {
		byte[] byteCipher = base64Decry(ciphertext);
		byte[] byteText = AESUtil.aesOpt(byteCipher, key, Cipher.DECRYPT_MODE);
		return new String(byteText, StandardCharsets.UTF_8);
	}

	/**
	 * aes 加密解密 
	 * @param mode: Cipher.ENCRYPT_MODE， Cipher.DECRYPT_MODE
	 */
	private static byte[] aesOpt(byte[] params, String key, int mode) throws Exception {
		// 创建AES的Key生产者
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(key.getBytes());
		kgen.init(128, secureRandom);
		// 根据用户密码，生成一个密钥
		SecretKey secretKey = kgen.generateKey();
		// 返回基本编码格式的密钥
		byte[] enCodeFormat = secretKey.getEncoded();
		// 转换为AES专用密钥
		SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
		// 创建密码器
		Cipher cipher = Cipher.getInstance("AES");
		// 初始化为解密模式的密码器
		cipher.init(mode, secretKeySpec);
		return cipher.doFinal(params);
	}

	/**
	 * base64加密
	 */
	private static String base64Encry(byte[] params) {
		return Base64.encodeBase64String(params);
	}

	/**
	 * base64解密
	 */
	private static byte[] base64Decry(String params) {
		return Base64.decodeBase64(params);
	}

	/**
	 * 将16进制转换为二进制
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1){
			return null;
		}
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	/**
	 * 将二进制转换成16进制
	 */
	public static String parseByte2HexStr(byte[] buf) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

}
